package com.yanqu.road.web.controller.usercenter.auto;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.admin.AdminResult2;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/usercenter/admin/auto")
public class SecondServerList {
    private static Logger logger = LogManager.getLogger(SecondServerList.class.getName());

    @ResponseBody
    @RequestMapping(value = "getSecondServerList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getSecondServerList(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        logger.info("request getSecondServerList");

        int channelId = jsonObject.getIntValue("channelId");


        long firstServerId = channelId * 100000 + 1;
        if (channelId == eChannelType.TaiWan.getValue()) {//台服的第一个服是4服
            firstServerId = channelId * 100000 + 4;
        }
        //把当前时间三天内结束的神秘商人活动都拉出来
        String needDateStr = DateHelper.getCurrentDateTimeString(DateHelper.getCurrentTime() - 3 * DateHelper.DAY_MILLIONS);
        Map<Integer, ActivityInfo> activityInfoMap = ActivityBussiness.getActivityInfoMap(eActivityType.MysteriousMerchantActivity, 1, needDateStr);

        ActivityInfo firstServerActivityInfo = null;
        long currentSecond = DateHelper.getCurrentTime() / 1000;
        int thisWeekId = DateHelper.getThisWeekId(1);

        AdminResult2 result = AdminResult2.defaultInstance();

        Map<String, List<Long>> mergeServerMap = new HashMap<>();//同参数的放一起

        List<ServerInfo> serverList = ServerListMgr.getServerList();
        for (ServerInfo serverInfo : serverList) {
            if (serverInfo.getChannelId() != channelId) {
                continue;
            }

            if (serverInfo.getServerType() != ServerListMgr.SERVER_TYPE_NORMAL) {
                continue;
            }

            if (!serverInfo.isOpen()) {
                continue;
            }

            //开服天数
            int openDays = ServerListMgr.getServerOpenDay(serverInfo);
            int firstRoundDays = ServerListMgr.getFirstOpenServerDays(serverInfo); //第一轮天数
            int secondRoundDays = firstRoundDays + 12;//第二轮固定天数

            if (openDays > secondRoundDays) {//超过第二轮最后一天的不会导活动了
                continue;
            }

            int dayType = 0; //固定排期
            if (openDays > firstRoundDays) {
                dayType = 1; //过渡排期
            }


            //第二轮第一天的真实日期
            long secondRoundFistDayTime = (DateHelper.getZeroTimeStamp(serverInfo.getOpenTime() * 1000) + firstRoundDays * DateHelper.DAY_MILLIONS);
            String secondTime = DateHelper.getCurrentDateTimeString(secondRoundFistDayTime);

            if (dayType == 0) {
                int serverWeekId = DateHelper.getThisWeekId(secondRoundFistDayTime / 1000, 1);
                if (serverWeekId != thisWeekId) {
                    continue;
                }
            }

            int interimDay = 0;//过度天数
            if (dayType == 1) {
                //找要进入过渡期的区服
                if (!Config.isDebug()) {//不是调试模式,限定了
                    if (openDays != secondRoundDays) {//不是第二轮固定天数最后一天的服
                        continue;
                    }
                }
                //算过渡期天数

                //运营注释:第2轮区服【神秘商人】的endTime和30100001中当前进行中的【神秘商人】的endTime的相差天数
                //相差天数为0时，则取30100001下一期【神秘商人】的时长，即跨服排期时间
                //程序翻译:取本服神秘商人活动的endTime和1服(台服是4服)神秘商人的endTime的相差天数
                long needSecond = serverInfo.getOpenTime() + (secondRoundDays - 1) * DateHelper.DAY_SECONDS;

                //找首个区服的第二轮固定天数最后一天的神秘商人活动
                if (firstServerActivityInfo == null) {
                    firstServerActivityInfo = findActivityInfoByServerId(activityInfoMap, firstServerId, needSecond);
                    if (firstServerActivityInfo == null) {
                        //找不到本期的,找上一期的
                        firstServerActivityInfo = findActivityInfoByServerId(activityInfoMap, firstServerId, needSecond - 3 * DateHelper.DAY_SECONDS);
                        if (firstServerActivityInfo == null) {//还找不到,异常了
                            return AdminResult.failMsg("找不到首服的神秘商人活动,serverId=" + firstServerId).toJsonString();
                        }
                    }
                }


                long secondRoundLastDayTime = DateHelper.getZeroTimeStamp(secondRoundFistDayTime + 12 * DateHelper.DAY_MILLIONS);
                long secondRoundLastDayTimeSecond = secondRoundLastDayTime / 1000;
                //算相差时间
                int diffDay = 0;
                if (firstServerActivityInfo.getEndTime() >= secondRoundLastDayTimeSecond) {
                    diffDay = (int) ((firstServerActivityInfo.getEndTime() - secondRoundLastDayTimeSecond) / DateHelper.DAY_SECONDS);
                } else {
                    diffDay = 3 - (int) ((secondRoundLastDayTimeSecond - firstServerActivityInfo.getEndTime()) / DateHelper.DAY_SECONDS);
                }

                //相差天数为0时，则取30100001下一期【神秘商人】的时长，即跨服排期时间
                if (diffDay == 0) {
                    ActivityInfo nextFirstServerActivityInfo = findActivityInfoByServerId(activityInfoMap, firstServerId, needSecond + 1 * DateHelper.DAY_SECONDS);
                    if (nextFirstServerActivityInfo != null) {
                        diffDay = (int) ((nextFirstServerActivityInfo.getEndShowTime() - nextFirstServerActivityInfo.getBeginShowTime()) / DateHelper.DAY_SECONDS);
                    } else {
                        diffDay = 3;
                    }
                }

                interimDay = diffDay;
            }

            String key = dayType + "|" + secondTime + "|" + interimDay;
            if (!mergeServerMap.containsKey(key)) {
                mergeServerMap.put(key, new ArrayList<>());
            }
            mergeServerMap.get(key).add(serverInfo.getServerId());

        }

        for (Map.Entry<String, List<Long>> entry : mergeServerMap.entrySet()) {
            String key = entry.getKey();

            if (entry.getValue().size() % 2 != 0) {
                //运营要求必须偶数,不是偶数不处理 要求by王裕
//                return AdminResult.failMsg("serverIds数量不是偶数,请检查").toJsonString();
                continue;
            }

            List<String> strings = StringUtils.stringToStringList(key, "\\|");
            /**
             * "groupId": "1",
             * "serverIds": "10001,1000
             * "type": 0,
             * "secondTime": "2024-08-1
             * "interimDay": 0,
             * "groupNum": "2",
             */
            JSONObject oneData = new JSONObject();
            oneData.put("groupId", 1);
            oneData.put("serverIds", StringUtils.listToString(entry.getValue(), ","));
            oneData.put("type", Integer.valueOf(strings.get(0)));
            oneData.put("secondTime", strings.get(1));
            oneData.put("interimDay", Integer.valueOf(strings.get(2)));
            oneData.put("groupNum", 2);

            result.getData().add(oneData);
        }

        return result.toJsonString();
    }

    /**
     * 在活动里找有本服的最新的活动
     *
     * @param activityInfoMap
     * @param serverId
     * @param needSecond      秒
     * @return
     */
    private static ActivityInfo findActivityInfoByServerId(Map<Integer, ActivityInfo> activityInfoMap, long serverId, long needSecond) {
        ActivityInfo findActivityInfo = null;
        for (ActivityInfo activityInfo : activityInfoMap.values()) {
            if (activityInfo.getEndShowTime() < needSecond || activityInfo.getBeginShowTime() > needSecond) {
                continue;
            }
            if (activityInfo.getServerIdList().contains(serverId)) {
                findActivityInfo = activityInfo;
                break;
            }
        }
        return findActivityInfo;
    }

    public static void main(String[] args) {
        Map<Integer, Integer> fistRoundDaysMap = new HashMap<>();
        fistRoundDaysMap.put(1, 13);
        fistRoundDaysMap.put(2, 19);
        fistRoundDaysMap.put(3, 18);
        fistRoundDaysMap.put(4, 17);
        fistRoundDaysMap.put(5, 16);
        fistRoundDaysMap.put(6, 15);
        fistRoundDaysMap.put(7, 14);

        List<ServerInfo> serverInfoList = new ArrayList<>();

        long compareTime = DateHelper.getCurrentTime();
        int thisWeekId = DateHelper.getThisWeekId(compareTime/1000,1);

        String str = "22100877=1732712400,22100876=1731931500,22100875=1731797400,22100874=1731326700,22100873=1731283500,22100872=1730721900,22100871=1730600220,22100870=1730076121,22100869=1729785901,22100868=1729406640,22100867=1729148760,22100866=1728785280,22100865=1728403500";
        for (String serverInfoStr : str.split(",")) {
            String[] serverInfoArr = serverInfoStr.split("=");
            ServerInfo serverInfo = new ServerInfo();
            serverInfo.setServerId(Long.valueOf(serverInfoArr[0]));
            serverInfo.setOpenTime(Long.valueOf(serverInfoArr[1]));
            serverInfoList.add(serverInfo);
        }

        Map<String, List<Long>> mergeServerMap = new HashMap<>();//同参数的放一起
        for (ServerInfo serverInfo : serverInfoList) {
            int openDays = DateHelper.calc2DateTDOADays(new Date(serverInfo.getOpenTime() * 1000), new Date(compareTime));
            int weekNum = DateHelper.getTodayWeek(serverInfo.getOpenTime() * 1000);//开服那天周几
            int firstRoundDays = fistRoundDaysMap.getOrDefault(weekNum, 0); //第一轮天数
            int secondRoundDays = firstRoundDays + 12;//第二轮固定天数

            if (openDays > secondRoundDays) {//超过第二轮最后一天的不会导活动了
                continue;
            }

            int dayType = 0; //固定排期
            if (openDays > firstRoundDays) {
                dayType = 1; //过渡排期
            }

            //第二轮第一天的真实日期
            long secondRoundFistDayTime = (DateHelper.getZeroTimeStamp(serverInfo.getOpenTime() * 1000) + firstRoundDays * DateHelper.DAY_MILLIONS);
            String secondTime = DateHelper.getCurrentDateTimeString(secondRoundFistDayTime);

            if (dayType == 0) {
                int serverWeekId = DateHelper.getThisWeekId(secondRoundFistDayTime / 1000, 1);
                if (serverWeekId != thisWeekId) {
                    continue;
                }
            }

            int interimDay = 0;//过度天数
            if (dayType == 1) {
                //找要进入过渡期的区服
                if (openDays != secondRoundDays) {//不是第二轮固定天数最后一天的服
                    continue;
                }
            }

            String key = dayType + "|" + secondTime + "|" + interimDay;
            if (!mergeServerMap.containsKey(key)) {
                mergeServerMap.put(key, new ArrayList<>());
            }
            mergeServerMap.get(key).add(serverInfo.getServerId());
        }

        for (Map.Entry<String, List<Long>> entry : mergeServerMap.entrySet()) {
            String key = entry.getKey();

            if (entry.getValue().size() % 2 != 0) {
                //运营要求必须偶数,不是偶数不处理 要求by王裕
                System.out.println("serverIds数量不是偶数,请检查" + key + ":" + StringUtils.listToString(entry.getValue(), ","));
            }else {
                System.out.println(key + ":" + StringUtils.listToString(entry.getValue(), ","));
            }
        }
    }
}
